import store from 'store';
import line from 'helpers/line';

const WORKING = 'AUTH_WORKING';
const CLEAR_ERROR = 'CLEAR_ERROR';
const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
const LOGIN_FAIL = 'LOGIN_FAIL';
const LOGOUT_SUCCESS = 'LOGOUT_SUCCESS';
const LOGOUT_FAIL = 'LOGOUT_FAIL';
const LOAD_USER_SUCCESS = 'LOAD_USER_SUCCESS';
const LOAD_USER_FAIL = 'LOAD_USER_FAIL';

const initialState = {
  working: false,
  error: null,
  user: null
};

export default function reducer(state = initialState, action = {}) {
  switch (action.type) {
    case WORKING:
      return {
        ...state,
        working: true
      };
    case CLEAR_ERROR:
      return {
        ...state,
        error: null
      };
    case LOAD_USER_SUCCESS:
      return {
        ...state,
        working: false,
        user: action.result
      };
    case LOAD_USER_FAIL:
      store.remove('sessionToken');
      return {
        ...state,
        working: false,
        error: action.error
      };
    case LOGIN_SUCCESS:
      store.set('sessionToken', action.result.sessionToken);
      return {
        ...state,
        working: false,
        user: action.result
      };
    case LOGIN_FAIL:
      return {
        ...state,
        working: false,
        user: null,
        error: action.error
      };
    case LOGOUT_SUCCESS:
      store.remove('sessionToken');
      return {
        ...state,
        working: false,
        user: null
      };
    case LOGOUT_FAIL:
      return {
        ...state,
        working: false,
        error: action.error
      };
    default:
      return state;
  }
}

export function isLoaded(globalState) {
  return globalState.auth && globalState.auth.loaded;
}

export function clearError() {
  return {
    type: CLEAR_ERROR
  };
}

export function login({ username, password }) {
  return {
    types: [WORKING, LOGIN_SUCCESS, LOGIN_FAIL],
    promise: () => line.login({ username, password })
  };
}

export function loadUserBySessionToken(sessionToken) {
  return {
    types: [WORKING, LOAD_USER_SUCCESS, LOAD_USER_FAIL],
    promise: () => line.loadUserBySessionToken(sessionToken)
  };
}

export function logout(sessionToken) {
  return {
    types: [WORKING, LOGOUT_SUCCESS, LOGOUT_FAIL],
    promise: () => line.logout(sessionToken)
  };
}
